<template>
  <div class="RobotManagement">
    <div class="search">
      注册时间：
      <el-date-picker
        v-model="userTimeVal"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
        value-format="yyyy-MM-dd"
        @change="focus"
      >
      </el-date-picker>
      <el-input placeholder="请输入" v-model="inputVal" clearable>
        <el-select v-model="select" slot="prepend" @change="change">
          <el-option label="ID" value="1"></el-option>
          <el-option label="手机号" value="2"></el-option>
        </el-select>
      </el-input>
      <el-button class="btn" @click="userListBtn">搜索查询</el-button>
    </div>
    <br />
    <el-radio-group v-model="system" fill="#39383D" @change="userListBtn">
      <el-radio-button label="">全部</el-radio-button>
      <el-radio-button label="ios">IOS</el-radio-button>
      <el-radio-button label="android">Android</el-radio-button>
    </el-radio-group>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="avatar" label="头像" width="180">
        <template slot-scope="scope">
          <el-image
            style="width: 50px; height: 50px; border-radius: 5px"
            :src="scope.row.avatar"
            :preview-src-list="[scope.row.avatar]"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="user_id" label="用户ID"> </el-table-column>
      <el-table-column prop="nickname" label="用户昵称"> </el-table-column>
      <el-table-column prop="mobile" label="手机号"> </el-table-column>
      <el-table-column prop="create_time" label="投放时间"> </el-table-column>
      <el-table-column prop="sex" label="性别" width="180">
        <template slot-scope="scope">
          {{ scope.row.sex == 1 ? "男" : "女" }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="180">
        <template slot-scope="scope">
          <!-- {{
            scope.row.status == 1
              ? "正常"
              : scope.row.status == 0
              ? "禁封"
              : "已注销"
          }} -->
          <el-button
            v-if="scope.row.status == 1"
            size="small"
            type="success"
            plain
            disabled
            >正常</el-button
          >
          <el-button
            v-if="scope.row.status == 2"
            size="small"
            type="danger"
            plain
            disabled
            >注销</el-button
          >
          <el-button
            v-if="scope.row.status === 0"
            size="small"
            type="warning"
            plain
            disabled
            >禁封</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="管理" width="300">
        <template slot-scope="scope">
          <el-button size="small" plain @click="edit(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="info"
            size="small"
            @click="logout(scope.row.user_id)"
            plain
            >注销</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="addDynamic(scope.row.user_id)"
            plain
            >添加动态</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="page"
      :limit.sync="pageSize"
      @pagination="getList"
    />
    <el-dialog
      title="添加动态"
      :visible.sync="centerDialogVisible"
      width="30%"
      center
      @close="closeDialog"
    >
      <el-form
        ref="form"
        :model="formA"
        label-position="right"
        label-width="80px"
        :rules="rules"
      >
        <el-form-item label="机器人ID" prop="user_id">
          <el-input v-model="formA.user_id" disabled></el-input>
        </el-form-item>
        <el-form-item label="选择心情" prop="mood_id">
          <el-select
            class="select"
            v-model="formA.mood_id"
            style="width: 100%"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options1"
              :key="item.id"
              :label="item.content"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择想做" prop="intend_id">
          <el-select
            class="select"
            v-model="formA.intend_id"
            style="width: 100%"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options2"
              :key="item.id"
              :label="item.content"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="formA.content"></el-input>
        </el-form-item>
        <el-form-item label="附件类型" prop="medias_type">
          <el-radio v-model="formA.medias_type" label="1">图片</el-radio>
          <el-radio v-model="formA.medias_type" label="2">视频</el-radio>
        </el-form-item>
        <el-form-item label="添加附件" prop="medias.path">
          <!-- <el-upload
                  class="avatar-uploader"
                  :http-request="upLoad"
                  :on-preview="handlePictureCardPreview"
                  :on-success="handleAvatarSuccess"
                  :show-file-list="false"
                  action
                >
                  <img
                    v-if="form.dialogImageUrl"
                    :src="form.dialogImageUrl"
                    class="avatar"
                    style="width: 200px; height: 180px"
                  />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload> -->
          <el-upload
            class="upload-demo"
            :http-request="upLoad"
            :before-upload="beforeUpload"
            :on-preview="handlePictureCardPreview"
            action
            drag
            ref="upload"
            multiple
            :limit="1"
            :on-exceed="handleExceed"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="编辑机器人" :visible.sync="bol" width="30%" center>
      <el-form
        ref="formB"
        :model="formB"
        label-position="right"
        label-width="80px"
        :rules="rules"
      >
        <el-form-item label="ID" prop="user_id">
          <el-input v-model="formB.user_id" disabled></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="formB.nickname"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="formB.sex" label="1">男</el-radio>
          <el-radio v-model="formB.sex" label="2">女</el-radio>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            action
            accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG,"
            :on-success="handleAvatarSuccess"
            :show-file-list="false"
            :http-request="upLoadA"
          >
            <img v-if="formB.img" :src="formB.img" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="bol = false">取 消</el-button>
        <el-button type="primary" @click="submit1">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  robotList,
  robotReleaseIdea,
  robotEdit,
} from "@/api/operationManagement";
import { logoutUser } from "@/api/UserManagement";
import Pagination from "@/components/Pagination"; // 分页
import { moodandintendList } from "@/api/operationManagement";
import { client } from "@/utils/oss.js";
import { ossToken } from "@/api/NotificationManagement";
export default {
  components: { Pagination },
  data() {
    return {
      userTimeVal: [],
      end_time: "",
      start_time: "",
      inputVal: "",
      select: "1",
      userId: "",
      mobile: "",
      system: "",
      tableData: [],
      page: 1,
      pageSize: 10,
      total: 0,
      centerDialogVisible: false,
      bol: false,
      pickerOptions: {
        disabledDate(platformValue) {
          return platformValue.getTime() > Date.now() - 8.64e6;
        },
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      formA: {
        user_id: "",
        mood_id: "",
        intend_id: "",
        medias_type: "1", //附件类型 1 - 图片 2 - 视频
        medias: {
          path: "",
          width: "0",
          height: "0",
        },
        content: "",
      },
      formB: {
        user_id: "",
        nickname: "",
        avatar: "",
        sex: "",
        img: "",
      },
      rules: {
        user_id: [{ required: true, message: "请输入ID", trigger: "blur" }],
        nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
        mood_id: [{ required: true, message: "请选择心情", trigger: "change" }],
        intend_id: [
          { required: true, message: "请选择想做", trigger: "change" },
        ],
        medias_type: [
          { required: true, message: "请选类型", trigger: "change" },
        ],
        sex: [{ required: true, message: "请选性别", trigger: "change" }],
        "medias.path": [
          { required: true, message: "请选类型", trigger: "change" },
        ],
      },
      options1: [], //心情
      options2: [], //想做
    };
  },
  methods: {
    //时间
    focus(time) {
      if (!this.userTimeVal) {
        this.userTimeVal = [];
      }
      this.start_time = this.userTimeVal[0];
      this.end_time = this.userTimeVal[1];
    },
    change() {
      this.inputVal = "";
      this.userId = "";
      this.mobile = "";
    },
    handlePictureCardPreview(file) {
      const url = URL.createObjectURL(file.raw);
      window.open(url, "_blank");
    },
    handleAvatarSuccess(res, file) {
      this.formB.img = URL.createObjectURL(file.raw);
    },
    beforeUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isImg =
        testmsg === "jpg" ||
        testmsg === "JPG" ||
        testmsg === "png" ||
        testmsg === "jpeg" ||
        testmsg === "JPEG" ||
        testmsg === "PNG";
      const isVidio =
        testmsg === "jpg" ||
        testmsg === "AVI" ||
        testmsg === "mov" ||
        testmsg === "rm" ||
        testmsg === "FLV" ||
        testmsg === "mp4" ||
        testmsg === "3GP" ||
        testmsg === "rmvb";
      if (isImg) {
        this.formA.medias_type = "1";
        return true;
      } else if (isVidio) {
        this.formA.medias_type = "2";
        return true;
      } else {
        this.$message({
          type: "error",
          message: "不支持上传文件格式",
        });
        return false;
      }
    },
    handleExceed() {
      this.$message.warning(`最多只能上传一个文件`);
    },
    //覆盖默认的上传行为，自定义上传的实现
    async upLoad(file) {
      await ossToken({
        type: this.formA.medias_type == 1 ? 0 : 1,
      }).then((res) => {
        if (res.code == 0) {
          this.dataObj = {
            accessKeyId: res.data.accessKey,
            accessKeySecret: res.data.accessSecret,
            securityToken: res.data.token,
            region: "oss-cn-hangzhou",
            bucket: res.data.bucket,
          };
        }
      });
      const self = this;
      let files = file.file,
        point = files.name.lastIndexOf("."),
        suffix = files.name.substr(point),
        fileName = files.name.substr(0, point),
        date = Date.parse(new Date());
      // fileNames = "/img/" + file.file.name;
      let path1 = this.formA.medias_type == 1 ? "/img/" : "/video/";
      let fileNames =
        path1 +
        Math.round(new Date() / 1000) +
        "." +
        file.file.name.substring(file.file.name.lastIndexOf(".") + 1);
      console.log(fileNames);
      // console.log(file.file.name.substring(file.file.name.lastIndexOf(".")+1));
      //fileNames上传文件的名称
      //file.file上传文件的内容
      client(this.dataObj)
        .multipartUpload(fileNames, file.file)
        .then((result) => {
          this.formA.medias.path = fileNames;
          //下面是如果对返回结果再进行处理，根据项目需要
          self.$message({
            message: "上传成功",
            type: "success",
          });
        })
        .catch((err) => {
          self.$message.error("上传失败");
        });
    },
    async upLoadA(file) {
      await ossToken({
        type: 0,
      }).then((res) => {
        if (res.code == 0) {
          this.dataObj = {
            accessKeyId: res.data.accessKey,
            accessKeySecret: res.data.accessSecret,
            securityToken: res.data.token,
            region: "oss-cn-hangzhou",
            bucket: res.data.bucket,
          };
        }
      });
      const self = this;
      let files = file.file,
        point = files.name.lastIndexOf("."),
        suffix = files.name.substr(point),
        fileName = files.name.substr(0, point),
        date = Date.parse(new Date());
      // fileNames = "/img/" + file.file.name;
      // let path1 = this.formA.medias_type == 1 ? "/img/" : "/video/";
      let fileNames =
        "/img/" +
        Math.round(new Date() / 1000) +
        "." +
        file.file.name.substring(file.file.name.lastIndexOf(".") + 1);
      console.log(fileNames);
      // console.log(file.file.name.substring(file.file.name.lastIndexOf(".")+1));
      //fileNames上传文件的名称
      //file.file上传文件的内容
      client(this.dataObj)
        .multipartUpload(fileNames, file.file)
        .then((result) => {
          this.formB.avatar = fileNames;
          //下面是如果对返回结果再进行处理，根据项目需要
          self.$message({
            message: "上传成功",
            type: "success",
          });
        })
        .catch((err) => {
          self.$message.error("上传失败");
        });
    },
    async getList() {
      const res = await robotList({
        page: this.page,
        pageSize: this.pageSize,
        userId: this.userId,
        mobile: this.mobile,
        system: this.system,
        start_time: this.start_time,
        end_time: this.end_time,
      });
      //   console.log(res);
      if (res.code == 0) {
        this.total = parseInt(res.data.count);
        this.tableData = res.data.list;
      }
    },
    // 搜索
    userListBtn() {
      this.page = 1;
      this.getList();
    },
    //获取心情列表
    async getMoodandintendList() {
      const res = await moodandintendList({ type: 1, pageSize: 100, page: 1 });
      if (res.code == 0) {
        this.options1 = res.data.list;
      }
      const res1 = await moodandintendList({ type: 2, pageSize: 100, page: 1 });
      if (res1.code == 0) {
        this.options2 = res1.data.list;
      }
    },
    // 添加动态
    addDynamic(id) {
      this.formA.user_id = id;
      this.centerDialogVisible = true;
    },
    submit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const res = await robotReleaseIdea(this.formA);
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: "提交成功！",
            });
            this.centerDialogVisible = false;
          }
        }
      });
    },
    closeDialog() {
      this.$refs.form.resetFields();
      this.formA.content = "";
      this.$refs.upload.clearFiles();
    },
    //编辑
    edit(obj) {
      this.formB.user_id = obj.user_id;
      this.formB.nickname = obj.nickname;
      this.formB.avatar = obj.avatar;
      this.formB.img = obj.avatar;
      this.formB.sex = obj.sex;

      this.bol = true;
    },
    submit1() {
      this.$refs.formB.validate(async (valid) => {
        if (valid) {
          const res = await robotEdit(this.formB);
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: "提交成功！",
            });
            this.getList();
            this.bol = false;
          }
        }
      });
    },
    //注销用户
    logout(id) {
      this.$confirm("是否要注销此账号释放手机号?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await logoutUser({
            userId: id,
          });
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: "注销成功!",
            });
            this.getList();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
  },
  created() {
    this.getList();
    this.getMoodandintendList();
  },
  watch: {
    inputVal: {
      immediate: true,
      handler(val) {
        if (this.select == 1) {
          this.userId = val;
        }
        if (this.select == 2) {
          this.mobile = val;
        }
      },
    },
  },
};
</script>

<style lang="less" scoped>
.RobotManagement {
  padding: 20px;
  .search {
    .el-input {
      width: 350px;
      margin: 0 20px;
    }
    /deep/ .el-input-group__prepend {
      width: 100px;
    }
    .el-button {
      margin-left: 20px;
    }
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    border: 1px dashed #d9d9d9;
    width: 178px;
    height: 178px;
    border-radius: 6px;
    display: block;
  }
}
</style>